package core

import (
	"fmt"
	"github.com/aceld/zinx/ziface"
	log "github.com/cihub/seelog"
	"time"
)

//装置对象

type Device struct {
	PID string		//装置ID
	Status int		//装置状态
	Operators int		//运营商
	Rssi	int			//信号值
	Conn ziface.IConnection //当前装置的连接

	LeakAlarmFlag uint16 //漏电报警标记
	TaAlarmFlag uint16 //Ta超温报警标记
	TbAlarmFlag uint16 //Tb超温报警标记
	TcAlarmFlag uint16 //Tc超温报警标记
	T0AlarmFlag uint16 //T0报警标记
	OverVoltageAlarmFlag uint16 //A相电压过压报警标记
	//UbOverVoltageAlarmFlag uint16 //B相电压过压报警标记
	//UcOverVoltageAlarmFlag uint16 //C相电压过压报警标记
	//UaUnderVoltageAlarmFlag uint16 //A相电压欠压报警标记
	//UbUnderVoltageAlarmFlag uint16 //B相电压欠压报警标记
	UnderVoltageAlarmFlag uint16 //C相电压欠压报警标记
	OverCurrentAlarmFlag uint16 //电流过流报警标记

}

//创建一个装置对象
func NewDevice(conn ziface.IConnection,deviceId string) *Device {

	device := &Device{
		PID: deviceId,
		Conn: conn,
	}

	return device
}

//发送注册应答到设备
func (d *Device) RegistrationResponse()  {
	//打包应答注册包
	registerPack :=make([]byte,0)
	d.SendMsg(0x74,registerPack)
}

//发送注册应答到设备
func (d *Device) DataResponse()  {
	//打包应答注册包
	registerPack :=make([]byte,0)
	d.SendMsg(0x92,registerPack)
}

//发送掉电应答到设备
func (d *Device) DevicePowerOffResponse()  {
	//打包掉电应答包
	registerPack :=make([]byte,0)
	d.SendMsg(0xdd,registerPack)
}

//发送时间校准应答到设备
func (d *Device) TimeCalibrationResponse() {
	//打包时间校准包
	timeCalPack := make([]byte,7)
	year := time.Now().Year()
	month := time.Now().Month()
	day   := time.Now().Day()

	hour := time.Now().Hour()
	minute := time.Now().Minute()
	seocnd := time.Now().Second()



	timeCalPack[0] = byte(year-2000)
	timeCalPack[1] = byte(month)
	timeCalPack[2] = byte(day)
	timeCalPack[3] = byte(time.Now().Weekday())
	timeCalPack[4] = byte(hour)
	timeCalPack[5] = byte(minute)
	timeCalPack[6] = byte(seocnd)

	d.SendMsg(0x93,timeCalPack)

}
func (d *Device) EventSetValResponse(){
	registerPack :=make([]byte,0)
	d.SendMsg(0x89,registerPack)
}
//报警设定值回应


//装置下线

func (d *Device) LostConnection()  {

}

/*
	发送消息给客户端
 */

func (d *Device) SendMsg(msgID uint8,data []byte)  {

	if d.Conn == nil{
		log.Debug("connection in player is nil")
		return
	}

	 strData := fmt.Sprintf("发送：%2x",data)
	 log.Debugf(strData)
	//调用Zinx框架的Send
	if err := d.Conn.SendMsg(msgID,data); err !=nil{
		fmt.Printf("Player SendMsg error!")
		return
	}

	return
}